<?php

namespace App\Models;

use App\Enums\BorrowStatus;
use Database\Factories\BorrowRecordFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class BorrowRecord extends Model
{
    use HasFactory;

    public static function newFactory(): BorrowRecordFactory
    {
        return BorrowRecordFactory::new();
    }

    protected $casts = [
        'borrow_date' => 'datetime',
        'due_date' => 'datetime',
        'returned'=> BorrowStatus::class
    ];

    protected  static function booted()
    {
        static::creating(function ($model) {
            $model->nos_sn = self::getBookBnString();
        });
    }

    private static function getBookBnString(): string
    {
        do {
            // 生成唯一的图书编号
            $bookNumber = substr(Str::uuid()->toString(),0,10);

            // 检查数据库中是否已存在相同的图书编号
            $exists = self::where('nos_sn', $bookNumber)->exists();

        } while ($exists);

        return $bookNumber;
    }

    public function member(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Member::class);
    }

    public function book(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Book::class);
    }
}
